package com.onec.service.auth.init;


import cn.hutool.core.collection.CollectionUtil;
import com.onec.service.api.content.AuthConstants;
import com.onec.service.auth.dao.ResourcePermissionRepository;
import com.onec.service.auth.entity.ResourcePermission;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 容器启动完成加载资源权限数据到缓存
 *
 * @author onec
 */
@Component
@AllArgsConstructor
@Slf4j
public class InitResourceRolesCacheRunner implements CommandLineRunner {

    @Autowired
    private RedisTemplate redisTemplate;

    private ResourcePermissionRepository permissionRepository;

    @Override
    public void run(String... args) {
        log.info("init resource s start ");
        redisTemplate.delete(AuthConstants.RESOURCE_ROLES_KEY);
        List<ResourcePermission> resources = permissionRepository.findAll();

        if (!resources.isEmpty()) {
            Map<String, List<ResourcePermission>> resourcesMap = resources
                    .stream()
                    .collect(Collectors.groupingBy(ResourcePermission::getUrl));
            Map<String, List<String>> resourceRoles = new HashMap<>();
            for (Map.Entry<String, List<ResourcePermission>> entry : resourcesMap.entrySet()) {
                List<ResourcePermission> permissionInfos = entry.getValue();
                List<String> stringList = permissionInfos
                        .stream()
                        .map(ResourcePermission::getName)
                        .map(roleId -> AuthConstants.AUTHORITY_PREFIX + roleId)
                        .collect(Collectors.toList());

                log.info("缓存资源权限：资源：{}获取到的权限集合：{}", entry.getKey(), stringList);
                if (CollectionUtil.isNotEmpty(stringList)) {
                    resourceRoles.put(entry.getKey(), stringList);
                }
            }
            redisTemplate.opsForHash().putAll(AuthConstants.RESOURCE_ROLES_KEY, resourceRoles);
            log.info("init resource  success ");
        }
    }
}
